package com.dayu.rabbitmq.topic;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.TimeoutException;

import com.dayu.rabbitmq.util.MQUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP.BasicProperties;

/**
 * @author dayu
 * @date 2019/02/20 Describe
 */
public class Get1 {
    private static final String QUEUE_NAME = "test_queue_topic_1";
    private static String EXCHANGE_NAME = "test_exchange_topic";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 获取连接
        Connection connection = MQUtil.getConnection();

        // 获取channel
        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 最后一个参数相当于路由日志级别
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "goods.add");

        // 保证一次只分发一个
        channel.basicQos(1);

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
                throws IOException {
                String message = new String(body, "utf-8");
                System.out.println("[1] read msg: " + message + "," + LocalDateTime.now());

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    channel.basicAck(envelope.getDeliveryTag(), false);
                    System.out.println("[1] done");
                }
            }
        };
        // 自动应答改成false
        boolean autoAck = false;
        // 添加监控
        channel.basicConsume(QUEUE_NAME, autoAck, consumer);

    }
}
